<template>
  <!-- 培训管理 -->
  <div class="_pageContent">
    <dataFilter :data="filterData" url="/activity/list" @search="search" ref="dataFilterRef"></dataFilter>

    <!-- 添加 -->
    <div class="_operation_add">
      <div style="color: #999;">
        <icon-list />
        培训列表
      </div>
      <div style="display: flex;flex-direction: row;gap: 10px;">
        <a-button type="primary" @click="addRecord">添加数据</a-button>
        <a-button type="primary" status="warning" @click="exportData">导出数据</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <a-table :data="data">
      <template #columns>
        <a-table-column title="ID" data-index="activityId" align="center"></a-table-column>
        <a-table-column title="活动封面" data-index="activityImg" align="center">
          <template #cell="{ record }">
            <img :src="imgUrl + record.activityImg" style="width: 100px;height: 60px;">
          </template>
        </a-table-column>
        <a-table-column title="活动名称" data-index="activityName" align="center"></a-table-column>
        <a-table-column title="活动开始时间" data-index="activityBeginTime" align="center">
          <template #cell="{ record }">
            {{ formatTime(record.activityBeginTime) }}
          </template>
        </a-table-column>
        <a-table-column title="活动结束时间" data-index="activityEndTime" align="center">
          <template #cell="{ record }">
            {{ formatTime(record.activityEndTime) }}
          </template>
        </a-table-column>
        <a-table-column title="报名人数" data-index="enrollment" align="center">
          <template #cell="{ record }">
            <div style="cursor: pointer; color: #4588ff;" @click="goRouter(record)">
              {{ record.enrollment }}
            </div>
          </template>
        </a-table-column>
        <a-table-column title="状态" data-index="status" align="center">
          <template #cell="{ record }">
            <template v-if="new Date(record.activityEndTime) <= new Date()">
              <span style="color: red;">已结束</span>
            </template>
            <template
              v-if="new Date(record.activityBeginTime) < new Date() && new Date(record.activityEndTime) > new Date()">
              <span style="color: green;">进行中</span>
            </template>
            <template v-if="new Date(record.activityBeginTime) > new Date()">
              <span style="color: #999;">未开始</span>
            </template>
          </template>
        </a-table-column>
        <a-table-column title="视频总共时长" data-index="videosLength" align="center"></a-table-column>
        <a-table-column title="操作" data-index="operation" align="center">
          <template #cell="{ record }">
            <div class="_operation_wrapper">
              <span class="_operation_edit" @click="updataRecord(record)">编辑</span>
              <span class="_operation_delete" @click="deleteRecord(record)">删除</span>
            </div>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>

  <!-- 新增窗口 or 修改窗口 -->
  <a-modal :visible="visible" :title="title" @ok="handleOk(title)" @cancel="visible = false" width="600px">

    <a-tabs>
      <a-tab-pane key="1" title="活动信息">
        <div
          style="display: flex;flex-direction: column;align-items: center;justify-content: center;margin-bottom: 10px;">
          <a-upload name="file" :action="url + '/file/upload'" :show-upload-list="false" accept="image/*"
            :show-file-list="false" @success="imgSuccess">
            <template #upload-button>
              <img v-if="form.activityImg" style="height: 100px;" :src="imgUrl + form.activityImg" alt="">
              <div v-else
                style="color: #999;height: 100px;width: 100px;display: flex;align-items: center;justify-content: center;border: 1px dashed #999;">
                上传封面</div>
            </template>
          </a-upload>
          <div style="font-weight: bold;">活动封面</div>
        </div>
        <a-form :model="form" ref="oneFormRef" :rules="oneRules">
          <a-form-item label="活动名称" field="activityName">
            <a-input v-model="form.activityName" />
          </a-form-item>
          <a-form-item label="活动时间" field="activityBeginTime">
            <a-range-picker style="width: 100%;" :model-value="[form.activityBeginTime, form.activityEndTime]"
              @change="changeActivityTime" show-time :allow-clear="false" />
          </a-form-item>
          <a-form-item label="活动组织者" field="organizer">
            <a-input v-model="form.organizer" />
          </a-form-item>
          <a-form-item label="活动内容" field="trainingContent">
            <a-input v-model="form.trainingContent" />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" title="地点信息">
        <a-form :model="addTrainData" ref="twoFormRef" :rules="twoRules">
          <a-form-item label="地点" name="address" field="address">
            <a-input v-model="addTrainData.address" />
          </a-form-item>

          <a-form-item label="时间" name="startDate" field="dataRange">
            <a-range-picker v-model="addTrainData.dataRange" @change="onChange" style="width: 100%;" :disabled-date="disabledDate" />

          </a-form-item>

          <a-form-item label="经度" name="longitude" field="longitude">
            <a-input v-model="addTrainData.longitude" />
          </a-form-item>
          <a-form-item label="纬度" name="latitude" field="latitude">
            <a-input v-model="addTrainData.latitude" />
          </a-form-item>
        </a-form>
        <div style="text-align: center;width: 100%;color: #999;">
          提示：贵溪市冶金大道4号卫健委10楼 经度:117.248884,纬度:28.299131
        </div>
        <div style="text-align: right;margin-top: 10px;">
          <a-button type="primary" status="success" @click="addTrainInfo">添加地点</a-button>
        </div>

        <div style="border-top: 1px solid #999;margin-top: 10px;padding-top: 10px;">
          <div v-for="(item, index) in trainInfo" :key="index">
            <div style="display: flex;align-items: center;justify-content: space-between;">
              <div
                style="padding: 10px;margin: 5px 0px 5px 20px;border-radius: 10px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);display: flex;gap: 10px;">
                <a-tooltip :content="item.address">
                  <div
                    style="font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px;">
                    地点:<text style="font-weight: normal;">{{ item.address }}</text></div>
                </a-tooltip>
                <a-tooltip :content="item.startDate + '-' + item.endDate">
                  <div
                    style="font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px;">
                    时间:<text style="font-weight: normal;">{{ item.startDate }} - {{ item.endDate }}</text></div>
                </a-tooltip>
                <a-tooltip :content="item.longitude + '-' + item.latitude">
                  <div
                    style="font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px;">
                    精度纬度:<text style="font-weight: normal;">{{ item.longitude }}-{{ item.latitude }}</text></div>
                </a-tooltip>
              </div>
              <div><a-button type="primary" status="danger" @click="deleteTrainInfo(index)">删除</a-button></div>
            </div>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

  </a-modal>
</template>
<script setup>
import { onMounted, ref } from "vue";
import dataFilter from "../../components/dataFilter.vue";
import { postActivityList, addActivity, updateActivity, deleteActivity, exportActivity } from "../../../api/activity";
import { postVideoList } from "../../../api/video";
import { Modal, Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';

const router = useRouter();
const dataFilterRef = ref(null);
const filterData = ref([
  {
    label: "活动名称",
    propName: "activityName",
    type: "input",
  }
]);
// 图片地址
const imgUrl = import.meta.env.VITE_APP_IMG_URL;
// 地址
const url = import.meta.env.VITE_APP_API_URL;
//tabel数据
const data = ref([]);

// 地点数据
const trainInfo = ref([{
  address: null,
  date: null,
  longitude: null,
  latitude: null
}]);
// 添加地址数据
const addTrainData = ref({
  dataRange: null,
  address: null,
  startDate: null,
  endDate: null,
  longitude: null,
  latitude: null
});

// 获取时间范围
const onChange = (dates) => {

  if (form.value.activityBeginTime == null) {
    Message.error('请选择活动时间!');
    addTrainData.value.dataRange = null;
    return;
  }

  if (dates && dates.length === 2) {
    addTrainData.value.startDate = dates[0];
    addTrainData.value.endDate = dates[1];
  }
}


// 添加地址数据
const addTrainInfo = () => {
  twoFormRef.value.validate().then(res => {
    if (!res) {
      trainInfo.value.push({
        address: addTrainData.value.address,
        startDate: addTrainData.value.startDate,
        endDate: addTrainData.value.endDate,
        longitude: addTrainData.value.longitude,
        latitude: addTrainData.value.latitude
      })
    }
  })
}

// 删除地点
function deleteTrainInfo(index) {
  trainInfo.value.splice(index, 1);
}


// 获取列表
function getList() {
  postActivityList({}).then(res => {
    data.value = res.data.sort((a, b) => b.activityId - a.activityId);
  })
}


const visible = ref(false);
const form = ref({
  activityImg: null,
  activityName: null,
  activityBeginTime: null,
  activityEndTime: null,
  enrollment: 0,
  videosInfo: null,
  trainingInfo: null,
  videosLength: null,
  organizer: null,
  trainingContent: null
});
const title = ref(null);
// 新增
function addRecord() {
  addTrainData.value = {
    dataRange: null,
    address: null,
    startDate: null,
    endDate: null,
    longitude: null,
    latitude: null
  };
  trainInfo.value = [];
  form.value = {
    activityImg: null,
    activityName: null,
    activityBeginTime: null,
    activityEndTime: null,
    enrollment: 0,
    videosInfo: null,
    trainingInfo: null,
    videosLength: null
  };

  visible.value = true;
  title.value = '新增数据';
}
// 修改
function updataRecord(record) {
  visible.value = true;
  form.value = JSON.parse(JSON.stringify(record));
  // 地点数据
  trainInfo.value = JSON.parse(record.trainingInfo);
  title.value = '修改数据';
}
// 图片上传成功
function imgSuccess(res) {
  const { response } = res;
  form.value.activityImg = response.data;
}
// 修改活动时间选择回调
function changeActivityTime(value) {

  addTrainData.value.dataRange = null;

  if (!value || value.length !== 2) return

  const [start, end] = value.map(v => dayjs(v))
  if (end.diff(start, 'day') < 0) {
    Message.error('结束时间不能早于开始时间')
    return
  }

  form.value.activityBeginTime = start.format()
  form.value.activityEndTime = end.format()

  // 重置地点时间选择
  addTrainData.value.startDate = null
}

// 将时间格式转换
function formatTime(time) {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const oneFormRef = ref(null);
const twoFormRef = ref(null);
// 表单验证
const oneRules = {
  activityName: [{ required: true, message: '请输入活动名称' }],
  activityBeginTime: [{ required: true, message: '请选择活动时间' }],
  organizer: [{ required: true, message: '请输入活动组织者' }],
  trainingContent: [{ required: true, message: '请输入活动内容' }],
}
const twoRules = {
  address: [{ required: true, message: '请输入地点' }],
  dataRange: [{ required: true, message: '请选择时间' }],
  longitude: [{ required: true, message: '请输入经度' }, {
    validator: (value, callback) => {
      if (isNaN(Number(value)) || value < -180 || value > 180) {
        callback('经度必须为-180到180之间的数字');
      } else {
        callback();
      }
    },
  }],
  latitude: [{ required: true, message: '请输入纬度' }, {
    validator: (value, callback) => {
      if (isNaN(Number(value)) || value < -90 || value > 90) {
        callback('纬度必须为-90到90之间的数字');
      } else {
        callback();
      }
    },
  }],
}
// 确定
function handleOk(title) {
  oneFormRef.value.validate().then(res => {
    if (!res) {
      if (form.value.activityImg == null) {
        return Message.error('请上传活动封面');
      }
      form.value.trainingInfo = JSON.stringify(trainInfo.value);
      if (title === '新增数据') {
        addActivity(form.value).then(res => {
          res.code == 200 && Message.success('新增成功');
          getList()
        })
      } else {
        updateActivity(form.value).then(res => {
          res.code == 200 && Message.success('修改成功');
          getList();
        })
      }
      visible.value = false;
    } else {
      Message.error('请检查数据');
    }
  })
}


// 删除
function deleteRecord(record) {
  Modal.info({
    title: '提示',
    content: '确定删除该数据吗？',
    closable: true,
    onOk: () => {
      deleteActivity(record.activityId).then(res => {
        Message.success('删除成功');
        getList();
      })
    }
  })
}
// 搜索
function search(res) {
  data.value = res.data
}
// 导出
function exportData() {
  exportActivity(dataFilterRef.value.filterParams)
}

// 点击报名人数跳转
function goRouter(record) {
  router.push({
    path: '/enlists',
    query: {
      name: record.activityName
    }
  })
}

// 在组件中新增日期禁用方法
const disabledDate = (current) => {
  const start = dayjs(form.value.activityBeginTime)
  const end = dayjs(form.value.activityEndTime)
  return current < start.startOf('day') || current > end.endOf('day')
}

onMounted(() => {
  getList();
})

</script>
<style scoped>
._operation_wrapper {
  display: flex;
  gap: 10px;
}

._operation_edit {
  color: #4588ff;
  cursor: pointer;
}

._operation_delete {
  color: #ff6a36;
  cursor: pointer;
}

._operation_add {
  margin-bottom: 10px;

  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>